<template>
  <div class="pr-report-problem-commissionner">
    <searchBar v-bind="searchProps" @search="search"> </searchBar>
    <div class="table-container mt-[16px]">
      <myTable v-bind="tableProps"> </myTable>
    </div>
    <div class="white-radius chart-container">
      <div id="myCharts1"></div>
    </div>
  </div>
</template>

<script setup name="statisticPrReportProblemCm">
import * as echarts from "echarts";
import { ref, computed, watch, reactive, onMounted, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";
import searchBar from "@/components/searchBar/index.vue";
import myTable from "@/components/myTable/index.vue";
// import { getPrRpOwnerList } from "@/api/statistic";
import { useSidebarStore } from "@/store/sidebar";

const { t, locale } = useI18n();
const sidebar = useSidebarStore();

let myCharts1 = null;
let query = reactive({
  startTime: null,
  endTime: null,
});
let searchProps = reactive({
  searchList: [
    {
      placeholder: "common.createTime",
      prop: "time",
      type: "datetimerange",
    },
  ],
});
let columns = ref([
  {
    label: "common.user",
    prop: "username",
    fixed: "left",
    width: 180,
  },
  {
    label: "common.email",
    prop: "email",
    width: 180,
  },
  {
    label: "page.manageTenantNumebr",
    prop: "shopCnt",
    width: 180,
  },
  {
    label: "page.issuesFound",
    prop: "issueCnt",
    width: 180,
  },
  {
    label: "page.followupCount",
    prop: "followupCnt",
    width: 180,
  },
  {
    label: "page.rectificationRate",
    prop: "processedPercentStr",
    width: 180,
  },
  {
    label: "page.aveProcessTime",
    prop: "averageProcessTimeStr",
    width: 180,
  },
]);
let tableProps = reactive({
  columns: columns.value,
  tableData: [], // 列表数据
  pagination: false,
  selection: false,
  loading: false,
  stickyIndexArr: [],
});
const search = (e, num) => {
  if (e.time === "") {
    query.startTime = null;
    query.endTime = null;
  } else {
    query.startTime = e.time[0];
    query.endTime = e.time[1];
  }
  getList();
};
const getList = async () => {
  tableProps.loading = true;
//   let res = await getPrRpOwnerList({
//     ...query,
//   });
  tableProps.loading = false;
  if (res.code === 200) {
    let list = res.data || [];
    // tableProps.stickyIndexArr = [list.length - 1, list.length - 2];
    tableProps.tableData = list;

    let legendData = [
      t("page.manageTenantNumebr"),
      t("page.issuesFound"),
      t("page.followupCount"),
      t("page.rectificationRate"),
    ];
    let yAxisTitle = [t("common.quantity"), t("common.percentage")];
    let xAxisData = [];
    list.forEach((v) => {
      xAxisData.push(v.username);
    });
    let prop = ["shopCnt", "issueCnt", "followupCnt", "processedPercent"];
    myCharts1 = initCharts(
      "myCharts1",
      list,
      yAxisTitle,
      legendData,
      xAxisData,
      prop,
      true,
      ["processedPercent"]
    );
  }
};
const resetCharts = () => {
  myCharts1 && myCharts1.resize();
};
const initCharts = (
  el,
  arr,
  yAxisTitle,
  legendData,
  xAxisData,
  prop,
  hasLine = false,
  lineProp
) => {
  // 根据prop进行分组,百分比而言，提示使用Str字段，显示使用值字段
  let myCharts = echarts.getInstanceByDom(document.getElementById(el));
  if (!myCharts) {
    myCharts = echarts.init(document.getElementById(el), "null");
  }
  let obj = {};
  prop.forEach((v) => {
    obj[v] = [...arr.map((item) => (item[v] ? item[v] : 0))];
  });
  // 绘制图表
  let options = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
      },
      formatter(params) {
        let str = `${params[0].axisValueLabel}<br/>`;
        params.forEach((item) => {
          let index1 = columns.value.findIndex((v) => t(v.label) === item.seriesName);
          if (index1 > -1) {
            let value = arr[item.dataIndex][columns.value[index1].prop];
            str += `${item.marker} ${item.seriesName}: ${
              value != null ? value : "0%"
            } <br/>`;
          }
        });
        return str;
      },
    },
    grid: {
      containLabel: true,
      left: "5%",
      right: "5%",
      bottom: "10%",
    },
    legend: {
      data: legendData,
      // icon: "circle",
      align: "left",
      type: "scroll",
    },
    xAxis: [
      {
        type: "category",
        axisTick: {
          alignWithLabel: true,
        },
        axisLabel: {
          interval: 0,
          // formatter(value) {
          //   return value.replace(/(.{8})/g, "$1\n");
          // },
          // overflow: "truncate",
        },
        data: xAxisData,
      },
    ],
    yAxis: [
      {
        type: "value",
        name: yAxisTitle[0],
        alignTicks: true,
        axisLine: {
          show: true,
        },
      },
    ],
    series: [],
  };
  if (hasLine) {
    options.yAxis.push({
      type: "value",
      name: yAxisTitle[1],
      position: "right",
      alignTicks: true,
      min: 0,
      max: 1,
      interval: 0.2,
      axisLine: {
        show: true,
      },
      axisLabel: {
        formatter: (value) => {
          return value * 100 + "%";
        },
      },
    });
  }
  Object.keys(obj).forEach((v, index) => {
    let data = obj[v];
    if (hasLine && lineProp.includes(v)) {
      options.series.push({
        data: data,
        type: "line",
        name: legendData[index],
        yAxisIndex: 1,
      });
    } else {
      options.series.push({
        data: data,
        type: "bar",
        name: legendData[index],
      });
    }
  });
  myCharts.setOption(options);
  return myCharts;
};
onUnmounted(() => {
  window.onresize = null;
});
onMounted(() => {
  window.onresize = resetCharts;
});
watch(
  () => sidebar.$state.collapse,
  (n) => {
    setTimeout(() => {
      resetCharts();
    }, 350);
  }
);
</script>

<style scoped lang="scss">
.chart-container {
  margin-top: 16px;
  box-sizing: border-box;
  #myCharts1 {
    height: 350px;
    width: 100%;
    overflow: hidden;
  }
}
</style>
